﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Model.EasyUI;
using SqlHelper;
using Utils.Types;

namespace Service.Permission
{
    public class UserMenuService : Repository<Model.Permission.UserMenu>
    {
        /// <summary>
        /// 获取菜单相关DataTable
        /// </summary>
        /// <param name="MenuType">菜单类型</param>
        /// <param name="UserID">用户ID</param> 
        /// <returns></returns>
        public DataTable GetUserMenuDataTable(int UserID, int MenuType)
        {
            string sql = $@"SELECT
                                menus.MenuID,
	                            usermenu.UserMenuID,
	                            usermenu.MenuName,
	                            usermenu.HasPermission,
	                            usermenu.MenuID,
	                            menus.Urls,
	                            menus.ParentID
                            FROM
	                            TUserMenu AS usermenu
                            INNER JOIN TMenu AS menus ON usermenu.MenuID = menus.MenuID
                            WHERE usermenu.UserID = {UserID}
                            AND menus.MenuType = {MenuType}
                            AND usermenu.HasPermission = 1
                            UNION
	                            SELECT
                                    menus.MenuID,
		                            usermenu.UserMenuID,
		                            usermenu.MenuName,
		                            usermenu.HasPermission,
		                            usermenu.MenuID,
		                            menus.Urls,
		                            menus.ParentID
	                            FROM
		                            TUserMenu AS usermenu
	                            INNER JOIN TMenu AS menus ON usermenu.MenuID = menus.MenuID
	                            WHERE
		                            menus.MenuID IN (
			                            SELECT
				                            menus.ParentID
			                            FROM
				                            TUserMenu AS usermenu
			                            INNER JOIN TMenu AS menus ON usermenu.MenuID = menus.MenuID
			                            WHERE usermenu.UserID = {UserID}
			                            AND menus.MenuType = {MenuType}
			                            AND usermenu.HasPermission = 1) ORDER BY menus.MenuID ASC ";
            return GetDataTableSQL(sql);
        }

        /// <summary>
        ///管理菜单
        /// </summary>
        /// <param name="MenuType">菜单类型</param>
        /// <param name="UserID">用户ID</param>
        /// <param name="ParentID">父级ID</param>
        /// <returns></returns>
        public DataTable ManagerTreeDataTable(int UserID, int ParentID = 0, int MenuType = 0)
        {
            string sql = $@"SELECT
	                        MenuID,
	                        Name,
	                        0 AS HasPermission,
	                        0 AS UserMenuID,
		                    Urls
                        FROM
	                        TMenu
                        WHERE
	                        MenuID NOT IN (
		                        SELECT
			                        MenuID
		                        FROM
			                        TUserMenu
                                where UserID ={UserID}
	                        )
                        AND ParentID = {ParentID}
                        AND MenuType = {MenuType}
                        UNION
	                       	SELECT
		                    MenuID,
		                    MenuName,
		                    HasPermission,
		                    UserMenuID,
		                    '' AS Urls
	                    FROM
		                    TUserMenu
	                    WHERE
		                    UserID ={UserID}
	                    AND MenuID IN (
		                    SELECT
			                    MenuID
		                    FROM
			                    TMenu
		                    WHERE 
                            ParentID = {ParentID}
                            AND MenuType = {MenuType} ) ";
            return GetDataTableSQL(sql);
        }

        /// <summary>
        /// 获取树形菜单 
        /// </summary>
        /// <param name="ParentID"></param> 
        public List<TreeBox> GetTreeBoxList(int UserID, int ParentID = 0, int MenuType = 0)
        {
            List<TreeBox> templist = new List<TreeBox>();

            var menudt = GetUserMenuDataTable(UserID, MenuType);

            if (menudt != null && menudt.Rows.Count > 0)
            {
                templist.AddRange(menudt.Rows.Cast<DataRow>().Select(item => new TreeBox
                {
                    id = item.GetDataRowValue("MenuID").IsNullOrEmpty() ? 0 : item.GetDataRowValue("MenuID").ConvertInt(),
                    text = item.GetDataRowValue("MenuName"),
                    parentid = item.GetDataRowValue("parentid").IsNullOrEmpty() ? 0 : item.GetDataRowValue("parentid").ConvertInt(),
                    urls = item.GetDataRowValue("Urls").IsNullOrEmpty() ? "" : (item.GetDataRowValue("Urls") + "?id=" + UserID)
                }));
            }

            var isparent = templist.Where(item => item.parentid == 0).ToList();
            var noparent = templist.Where(item => item.parentid != 0).ToList();

            foreach (var item1 in noparent)
            {
                foreach (var item2 in isparent)
                {
                    if (item1.parentid != item2.id) continue;
                    if (item2.children == null)
                        item2.children = new List<TreeBox>();
                    item2.children.Add(item1);
                }
            }

            return isparent;
        }

        /// <summary>
        /// 获取树形菜单 
        /// </summary>
        /// <param name="ParentID"></param> 
        public List<TreeBox> ManagerTree(int UserID, int ParentID = 0, int MenuType = 0)
        {
            List<TreeBox> list = new List<TreeBox>();
            var menudt = ManagerTreeDataTable(UserID, ParentID, MenuType);
            if (menudt != null && menudt.Rows.Count > 0)
            {
                foreach (DataRow item in menudt.Rows)
                {
                    TreeBox tree = new TreeBox()
                    {
                        id = (int)item["MenuID"],
                        text = item["Name"].ToString(),
                        @checked = item["HasPermission"].ConvertInt() > 0,
                        children = ManagerTree(UserID, (int)item["MenuID"], MenuType),
                        urls = item["Urls"].ToString(),
                    };
                    list.Add(tree);
                }
            }
            else
                list = null;

            return list;
        }

        /// <summary>
        /// 管理树形操作
        /// </summary>
        /// <param name="list"></param>
        /// <param name="UserID"></param>
        public bool UpdateTree(List<Model.Permission.UserMenu> list, int UserID)
        {
            var oldlist = GetListByValue<Model.Permission.UserMenu>(UserID, "UserID");
            if (oldlist != null && oldlist.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                    for (int j = 0; j < oldlist.Count; j++)
                        if (list[i].MenuID == oldlist[j].MenuID)
                        {
                            oldlist[j].HasPermission = list[i].HasPermission;
                            oldlist[j].UserID = UserID;
                        }
                return UpdateList(oldlist);
            }
            else
            {
                var templist = GetAllList<Model.Permission.Menu>();
                if (templist != null && templist.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                        for (int j = 0; j < templist.Count; j++)
                            if (list[i].MenuID == templist[j].MenuID)
                            {
                                list[i].UserID = UserID;
                                list[i].CreateTime = list[i].UpdateTime = System.DateTime.Now;
                                list[i].MenuName = templist[j].Name;
                                list[i].ParentID = templist[j].ParentID;
                            }
                    return InsertList(list);
                }
                return false;
            }
        }
    }
}
